<template>
<view>
	<cu-custom bgColor="bg-gradual-blue" :isBack="true">
		<block slot="backText">返回</block>
		<block slot="content">售后申请</block>
	</cu-custom>	
	<form class="service" @submit="submit">
		<view class="list">
			<view class="item" v-for="(item, index) in Info.shop_orders" :key="index">
				<image :src="item.default_imgurl"></image>
				<view>
					<view>
						<view>
							<text>{{ item.pname }}</text>
							<text class="margin-top-xs">{{ item.name }}</text>
						</view>
						<view>
							<text class="text-price text-red text-bold text-df">{{ item.now_price }}</text>
							<text class="text-right margin-top-xs">x{{ item.rcount }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="type">
			<view @tap="showService">
				<view>服务类型</view>
				<input type="text" disabled v-model="serviceType.name" name="name">
			</view>
			<view @tap="showReason">
				<view>售后原因</view>
				<input type="text" disabled v-model="params.reason" name="reason">
			</view>
			<view v-if="serviceType.id === 0">
				<view>退款金额</view>
				<input type="text" v-model.number="params.return_account" name="return_account" :placeholder="'最大退款金额不能超过'+maxMoney+'元'">
			</view>
		</view>
		<view class="reason">
			<textarea v-model="params.remark" name="remark" class="text" placeholder="请描述您的售后原因，不超过200字" auto-focus/>
		</view>
		<view class="img">
			<view class="title">图片<text>(选填，提供截图，总大小10M以下)</text></view>
			<view class="contain">
				<view @tap="preview(index)" v-if="list.length" v-for="(item, index) in list" :key="index" :style="{ backgroundImage: 'url('+item.path+')' }"></view>
				<image src="/static/upImg.png" class="addImg" @tap="chooseImg"></image>
			</view>
		</view>
		<view class="btn">
			<button type="warn" formType="submit">提交</button>
		</view>
	</form>	
</view>
</template>

<script>
	import { orderIndex, Refund, Reasonfund, Orfund } from '@/common/api/users'
	import { BagOrderDetail } from '@/common/api'
	import graceChecker from '@/common/utils/graceChecker'
	import { requestURL } from '@/common/utils/config'
	import { mapGetters } from 'vuex'	
	export default {
		name: 'service',
		data () {
			return {
				Info: {},
				list: [],
				serviceType: {
					name: '',
					id: ''
				},
				
				ReasonList: [],
				service: ['申请退款','申请退货'],
				maxMoney: 0,
				toWay: 0,
				params: {
					batchcode: '',
					remark: '',
					reason: '',
					return_account: '',
					sendstatus: 5
				}				
			}
		},
		onLoad(options) {
			this.params.batchcode = options.batchcode
			this.toWay = +options.tag ? options.tag : 0
			this.getDetail()
		},
		computed: {
			size () {
				if (this.list) {
					let size = this.list.reduce((prev, cur) => cur.size + prev, 0)
					return size / (1024 * 1024)
				}
				return 0
			},
			...mapGetters([
				'shop'
			])
		},
		watch: {
			'params.return_account' (val, oldval) {
				if (val > this.maxMoney) this.params.return_account = ''
			},
			'serviceType.id' (val, oldval) {
				this.params.return_account = ''
			}
		},
		methods: {
			async getDetail () {
				this.toWay ? await this.getBagInfo(this.params.batchcode) : await this.getInfo(this.params.batchcode)
				await this.getRefund(this.params.batchcode)
			},
			getBagInfo (batchcode) {
				return new Promise(resolve => {
					BagOrderDetail({ batchcode }).then(res => {
						if (!res.code) {
							const data = res.data[0]
							let info = {}
							info.CouponPrice = data.totalprice
							info.send_express_name = data.expressname
							info.address = data.location_p + data.location_c + data.location_a + data.address
							info.aftersale_type = 0
							info.batchcode = data.batchcode
							info.createtime = data.createtime
							info.confirm_sendtime = data.confirm_sendtime
							info.decrease_money = 0
							info.deductible_money = 0
							info.expressnum = data.expressnum
							info.id = data.p_id
							info.is_discuss = 0
							info.pay_currency = 0
							info.pay_money = data.package_price
							info.paystatus = data.paystatus
							info.phone = data.phone
							info.pid = data.p_id
							info.pname = data.package_name
							info.rcount = data.rcount
							info.return_status = data.return_status
							info.sendMoney = 0
							info.sendstatus = data.sendstatus
							info.shop_orders = [
								{ default_imgurl: data.default_head_imgurl, pname: data.package_name, rcount: data.rcount, now_price: data.package_price }
							]
							info.status = 0
							info.totalprice = data.totalprice
							info.user_name = data.name
							this.Info = info
						}
						resolve()
					})					
				})
			},
			getInfo (batchcode) {
				return new Promise(resolve => {
					orderIndex({ batchcode }).then(res => {
						let data = res[0]
						data.shop_orders.map(item => {
							item.now_price = this.utils.Fxied(this.utils.accEqu(item.totalprice, item.rcount))
							return item
						})
						this.Info = data
						if (this.Info.sendstatus !== 2) this.service.splice(1, 1)
						resolve()
					})					
				})
			},
			getRefund (batchcode) {
				return new Promise(resolve => {
					Refund({ batchcode }).then(res => {
						this.ReasonList = res.data.reson.map(item => item.reason)
						this.maxMoney = res.data.totalprice
						resolve()
					})					
				})
			},
			chooseImg () { // 选择上传图片
				uni.chooseImage({
					sizeType: ['original', 'compressed'],
					success: res => {
						this.list = [...this.list, ...res.tempFiles]
					}
				})
			},
			showReason () {
				uni.showActionSheet({
					itemList: this.ReasonList,
					success: result => {
						this.params.reason = this.ReasonList[result.tapIndex]
					}
				})
			},
			showService () {
				uni.showActionSheet({
					itemList: this.service,
					success: result => {
						this.serviceType.name = this.service[result.tapIndex]
						this.serviceType.id = result.tapIndex
						result.tapIndex ? this.params.sendstatus = 3 : this.params.sendstatus = 5
					}
				})
			},
			Refund () { // 退款
			    return new Promise(resolve => {
					Reasonfund(this.params).then(res => {
							if (!res.code) {
								uni.showModal({
									content: res.data,
									showCancel: false,
									success: res => {
										if (res.confirm) {
											uni.redirectTo({
												url: '/pages/orders/detail?batchcode='+this.params.batchcode
											})
										}
									}
								})
							} else {
							uni.showModal({
								content: res.msg,
								showCancel: false
							})
						}
						resolve()
					})					
				})
			},
			Rsfund () { // 退货
				return new Promise(resolve => {
					Orfund(this.params).then(res => {
							if (res.code === 400068) {
								uni.showModal({
									content: res.message,
									showCancel: false,
									success: res => {
										if (res.confirm) {
											uni.redirectTo({
												url: '/pages/orders/detail?batchcode='+this.params.batchcode
											})											
										}
									}
								})
							} else {
							uni.showModal({
								content: res.message,
								showCancel: false
							})
						}
						resolve()						
					})
				})
			},						
		   async submit (e) {
				let rule = []
				const normal = [
					{ name:"name", checkType : "notnull", errorMsg:"请选择服务类型" },
					{ name: "reason", checkType: "notnull", errorMsg: "请选择售后原因" },
					{ name: "remark", checkType: "notnull", errorMsg: "描述内容不可为空" }
				]
				const special = [
					{ name: "return_account", checkType: "notnull", errorMsg: "请输入退款金额" }
				]
				this.serviceType.id ? rule = normal : rule = normal.concat(special)
				const result = graceChecker.check(e.detail.value, rule)
				if (result) {
					const uploadImg = () => {
						return new Promise((resolve, reject) => {
							if (this.list.length) {
								this.list.forEach((item, index) => {
									uni.uploadFile({
										url: `${requestURL}/smallroutine/Reward/upload_eval`,
										filePath: item.path,
										name: 'img',
										formData: {
											customer_id: this.shop.customer_id,
											batchcode: this.batchcode
										},
										header: { 'Content-Type': 'multipart/form-data' },
										success: res => {
											if (index === this.list.length - 1) {
												resolve(true)
											}
										},
										fail: () => {
											reject(false)
										}
									})
								})
							} else {
								resolve(true)
							}
						})
					}
					uni.showLoading({ mask: true })
					await uploadImg()
					this.serviceType.id ? await this.Rsfund() :  await this.Refund()
					uni.hideLoading()
				} else {
					uni.showToast({
						icon: 'none',
						title: graceChecker.error
					})
				}
			}
		}
	}
</script>

<style lang="less" scoped>
@import '../../common/styles/variables.less';	
.service {
	.list {
		background:white;
		padding: 25upx 15px;
		.item {
			display: flex;
			position: relative;
			padding-bottom: 15px;
			margin-bottom: 15px;
			&:last-of-type {
				margin: 0;
				padding: 0;
				&::after {
					display: none;
				}
			}
			&::after {
				content: '';
				position: absolute;
				left: 0;
				width: 100%;
				border:1px dashed whitesmoke;
				bottom: 0;
			} 
			& > image {
				width: 146upx;
				height: 146upx;
				margin-right: 15px;				
			}
			& > view {
				&:nth-of-type(1) {
					flex:1;
					display: flex;
					flex-direction: column;
					flex-flow: column;
					justify-content: space-between;
					& > view {
						font-size: 26upx;
						&:nth-of-type(1) {
							display: flex;
							justify-content: space-between;
							& > view {
								&.price {
									display: flex;
									flex-direction: column;
									flex-flow: column;
									justify-content: space-between;
									align-items: flex-end;
									& > text {
										&:nth-of-type(1) {
											font-weight: 600;
											color: @red;
										}
									}
								}
							}
						}
						&:nth-of-type(2) {
							text-align: right;							
						}
						& > view {
							display: flex;
							flex-direction: column;
							flex-flow: column;
							text {
								&:nth-of-type(2) {
									font-size: @minSize;
									color: @gray;
								}
							}
						}
					}
				}
			}
		}
	}
	.type {
		margin: 15upx 0;
		padding: 0 15upx;
		align-items: center;
		background-color: white;
		& > view {
		    height: @height;			
			display: flex;
			justify-content: space-between;
			align-items: center;
			&:not(:nth-of-type(3)) {
				.arrowRight(#666, 0, 0);
			}
			&:not(:last-of-type) {
				.border-bottom;
			}
			& > view {
				font-size: @medium;
				&:nth-of-type(2) {
					padding-right: 30upx;
				}
			}
			& > input {
				flex: 1;
				text-align: right;
				margin-right: 30upx;
			}
		}
	}
	.reason {
		background-color: white;
		padding:15px;
		.text {
			width: 100%;
		}
	}
	.img {
		margin-top: 10px;
		.title {
			height: 80upx;
			line-height: 80upx;
			font-size:26upx;
			padding: 0 15px;
			background:white;
			box-sizing: border-box;
			border-bottom:1px solid #f1f1f1;
			text {
				font-size: 22upx;
				color:#666
			}
		}
		.contain {
			display: flex;
			flex-wrap: wrap;
			padding: 20upx 15px;
			background-color:white;
			& > image, & > view {
				width: 120upx;
				height: 120upx;
				margin: 10upx;
				display: block;
			}
			& > view {
				background-position: center top;
				background-size: cover;
				background-repeat: no-repeat;
			}
		}
	}
	.btn {
		margin: 60upx 15px;
	}	
}	
</style>
